﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentValidation;
using Microhard.WeixinMP.Models;
using Microhard.WeixinMP.Msg;
using Microhard.WeixinMP.Interfaces;
using Microhard.Core;
using FluentValidation.Results;

namespace Microhard.WeixinMP.Validators
{
    public class WXMPUserModelValidator : AbstractValidator<WXMPUserModel>
    {
        public WXMPUserModelValidator()
        {
            RuleSet("Insert", () =>
            {
                RuleFor(u => u.UserName).NotEmpty().WithMessage(MPUserMsg.NeedName).When(r => r.WXMPID == Guid.Empty);
                RuleFor(u => u.FakeID).NotEmpty().WithMessage(MPUserMsg.NeedFakeID).When(r => r.WXMPID == Guid.Empty);
                RuleFor(u => u.OpenID).NotEmpty().WithMessage(MPUserMsg.NeedOpenID).When(r => r.WXMPID == Guid.Empty);

                Custom(u =>
                {
                    IWXMPUser iUser = IoC.Resolve<IWXMPUser>();
                    if (iUser.IsUserExist(u.OpenID))
                    {
                        return new ValidationFailure("UserOpenIDIsExisting", "此用户已存在");

                    }
                    return null;
                });
            });
            RuleSet("Update", () =>
            {
                RuleFor(u => u.UserName).NotEmpty().WithMessage(MPUserMsg.NeedName);
                RuleFor(u => u.FakeID).NotEmpty().WithMessage(MPUserMsg.NeedFakeID);
                RuleFor(u => u.OpenID).NotEmpty().WithMessage(MPUserMsg.NeedOpenID);
            });
        }
    }
}
